package com.hhf.riceshopping.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.hhf.common.to.mq.OrderTo;
import com.hhf.common.to.mq.StockDetailTo;
import com.hhf.common.to.mq.StockLockedTo;
import com.hhf.common.utils.R;
import com.hhf.riceshopping.ware.entity.WareOrderTaskDetailEntity;
import com.hhf.riceshopping.ware.entity.WareOrderTaskEntity;
import com.hhf.riceshopping.ware.service.WareSkuService;
import com.hhf.riceshopping.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * 库存解锁有两种处理方案
     *  1.有可能是库存自己过期的处理
     *  2.也有可能是订单已经被关了的处理
     * @param to
     * @param message
     * @param channel
     * @throws IOException
     */

    @RabbitHandler  //1.有可能是库存自己过期的处理
    public void handleStockLoclkedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息...");
        try {
            wareSkuService.unlockStock(to);  //解库存
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    // 2.也有可能是订单已经被关了的处理，也就是害怕服务器因为卡顿或者网络等原因，
    // 订单还没有解锁，库存就判断订单还在创建订单中，还解锁不了，那这样的话就造成了永久解锁不了
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭准备解锁库存...");
        try{
            wareSkuService.unlockStock(orderTo);//解订单
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
}
